
import React, { Component,  } from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { Checkbox,Modal } from 'antd-mobile';
import * as Actions from '../../actions'
import Container from '../../components/Container'
import SwipeImage from '../../components/SwipeImage'
import ReactSwiper from '../../components/Scroller/ReactSwiper';
import SpecModal from './coms/specModal';
import MeScrollContainer from '../../components/MeScroll'
import * as utils from '../../utils'
import GiftItem from './coms/GiftItem'
const CheckboxItem = Checkbox.CheckboxItem;

 /*
  type=1:非赠品 加入购物车
  type=2:立即购买
   */
function closest(el, selector) {
  const matchesSelector = el.matches || el.webkitMatchesSelector || el.mozMatchesSelector || el.msMatchesSelector;
  while (el) {
    if (matchesSelector.call(el, selector)) {
      return el;
    }
    el = el.parentElement;
  }
  return null;
}
class Goods extends Component{
  static contextTypes={
    router:PropTypes.object.isRequired,
  }

  constructor(props) {
    super(props);
    this.state={
      visible:false,
      type:1,
      modal:false  //赠品/兑换商品选中的弹框
    }
  }
  componentDidMount(){
    let {actions,params} = this.props
    actions.getGoodsInfo({goods_id:params.id})
    
  }
  //立即购买/加入购物车
  onClickChoose(type){
    let {goodsInfo,params,actions,addCartInfo} =this.props 
    if(goodsInfo.goods_spec && goodsInfo.goods_spec.length>0){
      this.setState({
        visible:true,
        type
      })
    }else{
      //加入购物车
      if(type==1){
        let data={
          goods_id: params.id,
          goods_num:1,
          spec_str:''
        }
        utils.msg({text:'Add a shopping cart success！',code:1})
        actions.addCart(data)
      }else{   //立即购买
        goodsInfo.goods_num=1
        goodsInfo.exchange_goods=addCartInfo.exchange_goods||{}
        goodsInfo.gift_goods=addCartInfo.gift_goods||{}
        actions.addTempCart([goodsInfo])
        this.context.router.history.push(`/order/buyNow`)
      }
      
      
    }
    
  }
  //更新附属商品的数量(ps:只有兑换商品能修改数量)
  changeGiftGoodsNum =(gitem,num) =>{
    let {actions,addCartInfo} = this.props
    gitem.goods_num=num
    actions.addCart({exchange_goods:gitem})

  }

  //有sku时，回调onOK事件.type=1:加入购物车 type=2:立即购买
  callbackOnOk(data){
    let {params,actions,goodsInfo,addCartInfo} =this.props 
    let { type } =this.state
    data={...data,...{goods_id: params.id }}
    if(type ==1){
      actions.addCart(data)
      this.setState({
        visible:false
      })
    }else{
      data={...data,goods_name:goodsInfo.goods_name,goods_image:goodsInfo.goods_image}
      data.exchange_goods=addCartInfo.exchange_goods||{}
      data.gift_goods=addCartInfo.gift_goods||{}
      actions.addTempCart([{...data }])
      this.context.router.history.push(`/order/buyNow`)
    }
    
  }
  //附属商品checkbox事件
  checkboxChange(type,goodsId,checked){
    let {actions} =this.props 
      if(checked){  //取消选择
        type ==1 ?actions.addCart({gift_goods:null}):actions.addCart({exchange_goods:null})
      }else{
         this.context.router.history.push(`/subGoods/${goodsId}/${type}`) 
      } 
    
    
  }
  onWrapTouchStart = (e) => {
    // fix touch to scroll background page on iOS
    if (!/iPhone|iPod|iPad/i.test(navigator.userAgent)) {
      return;
    }
    const pNode = closest(e.target, '.am-modal-content');
    if (!pNode) {
      e.preventDefault();
    }
  }

  onClose = key => () => {
    this.setState({
      [key]: false,
    });
  }
  gotoSubGoods =(id,type) =>{
    this.context.router.history.push(`/subGoods/${id}/${type}`) 
  }
  
   render(){
    let {goodsInfo,addCartInfo} =this.props
    let {visible} =this.state
    return(
        <Container >
          <MeScrollContainer prefixCls={'bottom-isrcoll'} >
          <section className='goods-container'>
            {this.renderSwipe(goodsInfo)}
            {this.renderInfo(goodsInfo)}
            {/* this.renderSelectedInfo() */}

            {goodsInfo.goods_gift_list && goodsInfo.goods_gift_list.length>0 ? this.renderGift(goodsInfo.goods_gift_list,1):null}
            {goodsInfo.exchange_goods_list && goodsInfo.exchange_goods_list.length>0 ? this.renderGift(goodsInfo.exchange_goods_list,2):null}
            {this.renderDetail(goodsInfo)}
          </section>
          </MeScrollContainer>
          
          {this.renderBottom(goodsInfo)}

          {/*sku 弹框*/}
          {
            goodsInfo.goods_spec?
            <SpecModal onClose={(key)=>{ this.setState({[key]:false })}} 
                      onOK={(data)=>{ this.callbackOnOk(data) }}
                      visible={visible} 
                      data={goodsInfo}
                     
            />
            :null
          }
          {
            addCartInfo.gift_goods || addCartInfo.exchange_goods ?
            <div className='gift-btn' onClick={ () =>{ this.setState({ modal:true})}}><img className='gift-img' src={require('../../assets/images/gift.png')} /></div>
            :null

          }
          {/*赠品和兑换商品购物车*/}
          {this.renderModal()}
          
        </Container>
    )
  }
  //spec选中的情况
  renderSelectedInfo(){
    let {addCartInfo,goodsInfo} =this.props
    if(addCartInfo.goods_id != goodsInfo.goods_id || !goodsInfo.goods_spec) return null
    return(
      <div className='li-selected-info'>
        <p className='dl'>Selected：</p>
        <div className='dd'>
          <div className='le'>{addCartInfo.spec_str}</div>
          <div className='re red'>x{addCartInfo.goods_num}</div>
        </div>
      </div>
      )
  }
  // 图片轮播
  renderSwipe(goodsInfo){
    if(!goodsInfo.head_imgs) return null

    return <SwipeImage height={'300px'} bannelThumbImgs={goodsInfo.head_imgs} loop={true}
     onTouch={(item)=>{
      
      
    }} />
  }
  // 商品信息
  renderInfo(goodsInfo){
    return(
      <div className="li-de-info">
        <div className="li-de-left">
          <div className="name">{goodsInfo.goods_name}</div>
          <div className="price">
          <span>$ {goodsInfo.goods_cost_price||0}</span>
          </div>
          <div className="size">
            MOQ:{goodsInfo.goods_min_order||0}
          </div>
          <div className='tags'>
            {
              goodsInfo.goods_use_score>0?<span className='tag tag-1'>The integral is worth ${goodsInfo.goods_use_score}</span>:null
            }
            {
              goodsInfo.goods_return_score>0?<span className='tag tag-2'>After the purchase of {goodsInfo.goods_return_score} points</span>:null
            }
            
            
          </div>

        </div>
        
      </div>
    )
  }
  // 商品详情
  renderDetail(goodsInfo){
    if(!goodsInfo.image) return null
    return(
      <div className="li-de-context">
        <div className="li-de-title"><span className="line"></span>DETAIL<span className="line"></span></div>
          <div className="li-de-detail">
              {
                goodsInfo.image.map((item,i)=>{
                  return(
                    <div key={i}>
                      <img src={item.image_name} alt=""/>
                    </div>
                  )
                })
              }
            </div>
      </div>
    )
  }
  // 底部按钮
  renderBottom(goodsInfo){
    return(
      <div className="bottom bordertop" >
        <div className="li-chunks-btns">
          <div className="li-chunk-btn btn2" onClick={this.onClickChoose.bind(this,1)}>ADD TO CART</div>
          {/*<div className="li-chunk-btn btn2" onClick={this.onClickChoose.bind(this,2)}>buy now</div>*/}
        </div>
      </div>
    )
  }
  //赠品 and 兑换商品选中列表
  renderModal(){
    let {addCartInfo} =this.props
    return(
      <Modal
          wrapClassName='gift-list-modal'
          visible={ this.state.modal}
          transparent
          maskClosable={true}
          onClose={this.onClose('modal')}
          title="Gift"
          wrapProps={{ onTouchStart: this.onWrapTouchStart }}
        >
          <div className='goods-gift-plane' style={{ height: 300, overflow: 'scroll' }}>
          {
            addCartInfo.gift_goods?
            <GiftItem 
            type ={1}
              gitem={ addCartInfo.gift_goods} 
              changeGiftGoodsNum={this.changeGiftGoodsNum} 
              onClickLeft_gift={this.gotoSubGoods}
              />
              :null
          }
          {
            addCartInfo.exchange_goods?
            <GiftItem 
              type={2}
              gitem={ addCartInfo.exchange_goods} 
              changeGiftGoodsNum={this.changeGiftGoodsNum} 
              onClickLeft_gift={this.gotoSubGoods}
              />
              :null
          }
            
          
          </div>
          
        </Modal>
      )
  }
  //促销活动
  renderGift(dataSource,type){
    let {addCartInfo} =this.props 
    const row = (rowData, rowID)=>{
      return (
        <div className="gift-item" key={rowID}>
        {
          do{
                if(type ==1)
                {
                  addCartInfo.gift_goods && addCartInfo.gift_goods.goods_id == rowData.goods_id?
                  <CheckboxItem checked={true} onChange={this.checkboxChange.bind(this,type,rowData.goods_id,true)} className='checkbox'>
                  </CheckboxItem>
                  :
                  <CheckboxItem checked={false} onChange={this.checkboxChange.bind(this,type,rowData.goods_id,false)} className='checkbox'></CheckboxItem>
                }
                  
                else
                {
                  addCartInfo.exchange_goods &&  addCartInfo.exchange_goods.goods_id == rowData.goods_id?
                  <CheckboxItem checked={true} onChange={this.checkboxChange.bind(this,type,rowData.goods_id,true)} className='checkbox'>
                  </CheckboxItem>
                  :
                  <CheckboxItem checked={false} onChange={this.checkboxChange.bind(this,type,rowData.goods_id,false)} className='checkbox'></CheckboxItem>

                }

              }
        }
          
          <div className="img" onClick={ this.gotoSubGoods.bind(this,rowData.goods_id,type)}>
            <img src={rowData.goods_image}/>
          </div>
          <div className='gift-info' onClick={ this.gotoSubGoods.bind(this,rowData.goods_id,type)}>
            <p className="name line-clamp-2">{ rowData.goods_name}</p>
            {
              type ==1 ? null : 
              <p className="price red">${rowData.goods_price} 
              </p>
            }
            
          </div>
          
        </div>    
      )
      }
    return(
      <div className='li-de-gift'>
        <div className='title'>
          {
              do{
                if(type ==1)
                  'Buy 1 get 1 Free'
                else
                  'Exchange of goods'
              }
              
            }
        </div>
        <div>
        {
          dataSource.map((item,i) =>( row(item,i) ))
        }
        </div>
      </div>
      )
  }
 
}


function mapStateToProps(state){
  
  return {
    goodsInfo:state.goodsInfo.toJS(),
    addCartInfo:state.addCartInfo.toJS()
  }
}
function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(Actions, dispatch)
  }
}
export default  connect(
  mapStateToProps,
  mapDispatchToProps
)(Goods)
